package com.jielihaofeng.netty.ppt;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author Johnnie Wind
 * @description
 * @date 2021/10/26 16:08
 */
public class Reactor implements Runnable{
    // Selector选择器
    final Selector selector;
    // 服务端Socket通道
    final ServerSocketChannel serverSocket;

    Reactor(int port) throws IOException {
        // 创建 Selector
        selector = Selector.open();
        // 创建 ServerSocketChannel
        serverSocket = ServerSocketChannel.open();
        // ServerSocketChannel 绑定端口
        serverSocket.bind(new InetSocketAddress(port));
        // 把ServerSocketChannel注册到Selector，关注OP_ACCEPT连接事件
        SelectionKey sk = serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        // 把一个Acceptor接收器实例作为附件
        sk.attach(new Acceptor());
    }
    /*
     * 也可以使用SPI提供接口：
     * SelectorProvider p = SelectorProvider.provider();
     * selector = p.openSelector();
     * serverSocket = p.openServerSocketChannel();
     */

    // class Reactor continued
    @Override
    public void run() {
        // 通常在新线程中执行
        try {
            // 如果当前线程没有中断一直执行
            while (!Thread.interrupted()) {
                // 查询选择器中获取已经准备好的并且注册过的操作
                selector.select();
                // 获取所有已经准备好的并且注册过的操作
                Set selected = selector.selectedKeys();
                Iterator it = selected.iterator();
                while (it.hasNext()){
                    // 调度并处理事件
                    dispatch((SelectionKey)(it.next()));
                }
                // 移除选择器
                selected.clear();
            }
        } catch (IOException ex) {
            /* ... */
        }
    }

    // 调度并处理事件
    void dispatch(SelectionKey k) {
        // 获取SelectionKey上绑定的程序，不为空就执行
        Runnable r = (Runnable)(k.attachment());
        if (r != null) {
            r.run();
        }
    }

    // class Reactor continued
    // 创建接收器
    class Acceptor implements Runnable {
        @Override
        public void run() {
            try {
                // 获取客户端连接
                SocketChannel c = serverSocket.accept();
                if (c != null) {
                    // 处理客户端连接
//                    new ThradPoolHandler(selector, c);
                }
            } catch (IOException ex) {
                /* ... */
            }
        }
    }
}
